﻿using StudentLive.Common;
using StudentLive.DataModel;
using StudentLive.InnerPages;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Input;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Search Contract item template is documented at http://go.microsoft.com/fwlink/?LinkId=234240

namespace StudentLive
{
    /// <summary>
    /// This page displays search results when a global search is directed to this application.
    /// </summary>
    public sealed partial class SearchResultsPage : StudentLive.Common.LayoutAwarePage
    {
        private Dictionary<string, List<object>> _results = new Dictionary<string, List<object>>();

        public SearchResultsPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            var queryText = navigationParameter as String;

            // TODO: Application-specific searching logic.  The search process is responsible for
            //       creating a list of user-selectable result categories:
            //
            //       filterList.Add(new Filter("<filter name>", <result count>));
            //
            //       Only the first filter, typically "All", should pass true as a third argument in
            //       order to start in an active state.  Results for the active filter are provided
            //       in Filter_SelectionChanged below.

            var filterList = new List<Filter>();
            filterList.Add(new Filter("All", 0, true));

            if (queryText != null)
            {
                string query = queryText.ToLower();
                Search(filterList, query, "Lesson Plans", LiveDataSource.GetAllUnits("AllUnits").Cast<object>().ToList());
                Search(filterList, query, "Learning Resources", LiveDataSource.GetAllLessons("AllLessons").Cast<object>().ToList());
                Search(filterList, query, "Units", LiveDataSource.GetAllCoursePlans("AllCoursePlans").Cast<object>().ToList());
                Search(filterList, query, "My Teachers", LiveDataSource.GetAllTeachers().Cast<object>().ToList());
                Search(filterList, query, "My Buddies", LiveDataSource.GetAllStudents().Cast<object>().ToList());

                // Communicate results through the view moacdel
                this.DefaultViewModel["QueryText"] = '\u201c' + queryText + '\u201d';
                this.DefaultViewModel["Filters"] = filterList;
                this.DefaultViewModel["ShowFilters"] = filterList.Count > 1;
            }

        }

        /// <summary>
        /// Invoked when a filter is selected using the ComboBox in snapped view state.
        /// </summary>
        /// <param name="sender">The ComboBox instance.</param>
        /// <param name="e">Event data describing how the selected filter was changed.</param>
        void Filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Determine what filter was selected
            var selectedFilter = e.AddedItems.FirstOrDefault() as Filter;
            if (selectedFilter != null)
            {
                // Mirror the results into the corresponding Filter object to allow the
                // RadioButton representation used when not snapped to reflect the change
                selectedFilter.Active = true;

                // TODO: Respond to the change in active filter by setting this.DefaultViewModel["Results"]
                //       to a collection of items with bindable Image, Title, Subtitle, and Description properties
                this.DefaultViewModel["Results"] = _results[selectedFilter.Name];

                // Ensure results are found
                object results;
                ICollection resultsCollection;
                if (this.DefaultViewModel.TryGetValue("Results", out results) &&
                    (resultsCollection = results as ICollection) != null &&
                    resultsCollection.Count != 0)
                {
                    VisualStateManager.GoToState(this, "ResultsFound", true);
                    return;
                }
            }

            // Display informational text when there are no search results.
            VisualStateManager.GoToState(this, "NoResultsFound", true);
        }

        /// <summary>
        /// Invoked when a filter is selected using a RadioButton when not snapped.
        /// </summary>
        /// <param name="sender">The selected RadioButton instance.</param>
        /// <param name="e">Event data describing how the RadioButton was selected.</param>
        void Filter_Checked(object sender, RoutedEventArgs e)
        {
            // Mirror the change into the CollectionViewSource used by the corresponding ComboBox
            // to ensure that the change is reflected when snapped
            if (filtersViewSource.View != null)
            {
                var filter = (sender as FrameworkElement).DataContext;
                filtersViewSource.View.MoveCurrentTo(filter);
            }
        }

        /// <summary>
        /// View model describing one of the filters available for viewing search results.
        /// </summary>
        private sealed class Filter : StudentLive.Common.BindableBase
        {
            private String _name;
            private int _count;
            private bool _active;

            public Filter(String name, int count, bool active = false)
            {
                this.Name = name;
                this.Count = count;
                this.Active = active;
            }

            public override String ToString()
            {
                return Description;
            }

            public String Name
            {
                get { return _name; }
                set { if (this.SetProperty(ref _name, value)) this.OnPropertyChanged("Description"); }
            }

            public int Count
            {
                get { return _count; }
                set { if (this.SetProperty(ref _count, value)) this.OnPropertyChanged("Description"); }
            }

            public bool Active
            {
                get { return _active; }
                set { this.SetProperty(ref _active, value); }
            }

            public String Description
            {
                get { return String.Format("{0} ({1})", _name, _count); }
            }
        }

        private void OnItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the page showing the recipe that was clicked
            BindableBase item = (BindableBase)e.ClickedItem;
            if (item.GetType() == typeof(LessonPlanItem))
            {
                var lessonPlanItem = ((LessonPlanItem)e.ClickedItem);
                var unitItem = lessonPlanItem.Unit;
                this.Frame.Navigate(typeof(LessonDetails), unitItem.CoursePlanID);
            }
            else if (item.GetType() == typeof(ResourceItem) || item.GetType() == typeof(StudentItem) || item.GetType() == typeof(TeacherItem))
            {
                resultsGridView.SelectedItem = item;
            }
            else if (item.GetType() == typeof(UnitItem))
            {
                var unitItem = ((UnitItem)e.ClickedItem);
                this.Frame.Navigate(typeof(LessonDetails), unitItem.CoursePlanID);
            }
        }

        private void Search(List<Filter> filterList, string query, string groupTitle, List<object> groups)
        {

            var all = new List<object>();
            foreach (dynamic group in groups)
            {
                dynamic smallItems = null;
                List<object> items = new List<object>();
                if (group.GetType() == typeof(UnitItem))
                {
                    smallItems = group.Lessons;
                }
                else if (group.GetType() == typeof(LessonPlanItem))
                {
                    smallItems = group.Resources;
                }
                else if (group.GetType() == typeof(CoursePlanItem))
                {
                    smallItems = group.Units;
                }
                else if (group.GetType() == typeof(TeachersGroup))
                {
                    smallItems = group.Teachers;
                }
                else if (group.GetType() == typeof(StudentsGroup))
                {
                    smallItems = group.Students;
                }

                if (smallItems != null)
                {
                    foreach (var item in smallItems)
                    {
                        if (item.Name.ToLower().Contains(query))
                        {
                            all.Add(item);
                            items.Add(item);
                        }
                    }
                    if (_results.ContainsKey(groupTitle))
                    {
                        var itemList1 = _results[groupTitle];
                        var allItems = itemList1.Concat(items);
                        _results[groupTitle] = allItems.ToList();
                    }
                    else
                    {
                        _results.Add(groupTitle, items.Cast<object>().ToList());
                    }

                    var check = filterList.Find(x => x.Name == groupTitle);
                    if (check != null)
                    {
                        check.Count = check.Count + items.Count;
                    }
                    else
                    {
                        filterList.Add(new Filter(groupTitle, items.Count, false));
                    }

                }
            }
            if (_results.ContainsKey("All"))
            {
                var allItems = _results["All"].Concat(all);
                _results["All"] = allItems.ToList();
            }
            else
            {
                _results.Add("All", all);
            }
            filterList[0].Count = _results["All"].Count;
        }

        async void DefaultLaunch(string path)
        {
            // Path to the file in the app package to launch

            var file = await StorageFile.GetFileFromPathAsync(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, path));

            if (file != null)
            {
                // Set the option to show the picker
                //var options = new Windows.System.LauncherOptions();
                //options.DisplayApplicationPicker = true;

                // Launch the retrieved file
                bool success = await Windows.System.Launcher.LaunchFileAsync(file);
                if (success)
                {
                    // File launched
                }
                else
                {
                    // File launch failed
                }
            }
            else
            {
                // Could not find file
            }
        }

        void startLoadingWithParent(StackPanel parent)
        {
            ProgressBar bar = new ProgressBar();
            bar.IsIndeterminate = true;
            bar.Margin = new Thickness(0, 10, 0, 0);
            bar.Width = parent.Width;
            parent.Children.Insert(2, bar);
        }

        void stopLoadingWithParent(StackPanel parent)
        {
            foreach (var item in parent.Children)
            {
                if ((item as ProgressBar) != null)
                {
                    parent.Children.Remove(item);
                }
            }
        }

        private async void OnDownloadButtonClicked(object sender, RoutedEventArgs e)
        {
            var item = (ResourceItem)resultsGridView.SelectedItem;
            StackPanel panel = (sender as Button).Parent as StackPanel;
            startLoadingWithParent(panel);
            await LiveDataSource.DownloadResource(item);
            stopLoadingWithParent(panel);
            OpenButton.Visibility = Visibility.Visible;
            FavoriteButton.Visibility = Visibility.Visible;
            DownloadButton.Visibility = Visibility.Collapsed;
            FavoriteButton.Visibility = Visibility.Visible;
        }

        private void OnOpenButtonClicked(object sender, RoutedEventArgs e)
        {
            var item = (ResourceItem)resultsGridView.SelectedItem;
            if (item.IsDownloaded)
                DefaultLaunch(item.LocalPath);
        }

        private void FavoriteButtonClick(object sender, RoutedEventArgs e)
        {
            var lr = ((ResourceItem)(resultsGridView.SelectedItem));
            lr.IsFavoured = !lr.IsFavoured;
            LiveDataSource.UpdateLearningResource(lr);
            if (lr.IsFavoured)
            {
                UnFavorButton.Visibility = Visibility.Visible;
                FavoriteButton.Visibility = Visibility.Collapsed;
            }
            else
            {
                UnFavorButton.Visibility = Visibility.Collapsed;
                FavoriteButton.Visibility = Visibility.Visible;
            }


        }

        private async void SendEmailButton_Click(object sender, RoutedEventArgs e)
        {
            var user = (dynamic)resultsGridView.SelectedItem;
            string address = user.Email;
            string body = string.Format("\n\n\n\n\nSent By LearN’Go.");
            var mailto = new Uri(string.Format("mailto:?to={0}&body={1}", address, body));
            await Windows.System.Launcher.LaunchUriAsync(mailto);
        }

        private void resultsGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (resultsGridView.SelectedItem != null)
            {
                if (resultsGridView.SelectedItem.GetType() == typeof(ResourceItem))
                {
                    var resourceItem = (ResourceItem)resultsGridView.SelectedItem;
                    if (resourceItem != null)
                    {
                        SendMail.Visibility = Visibility.Collapsed;
                        BottomAppBar.Visibility = Visibility.Visible;
                        BottomAppBar.IsOpen = true;
                        if (resourceItem.IsDownloaded == true)
                        {
                            OpenButton.Visibility = Visibility.Visible;
                            DownloadButton.Visibility = Visibility.Collapsed;
                            if (resourceItem.IsFavoured)
                            {
                                FavoriteButton.Visibility = Visibility.Collapsed;
                                UnFavorButton.Visibility = Visibility.Visible;
                            }
                            else
                            {
                                FavoriteButton.Visibility = Visibility.Visible;
                                UnFavorButton.Visibility = Visibility.Collapsed;
                            }
                        }
                        else
                        {
                            OpenButton.Visibility = Visibility.Collapsed;
                            DownloadButton.Visibility = Visibility.Visible;
                            UnFavorButton.Visibility = Visibility.Collapsed;
                            FavoriteButton.Visibility = Visibility.Collapsed;
                        }
                    }
                    else
                        BottomAppBar.Visibility = Visibility.Collapsed;
                }
                else if (resultsGridView.SelectedItem.GetType() == typeof(StudentItem) || resultsGridView.SelectedItem.GetType() == typeof(TeacherItem))
                {
                    OpenButton.Visibility = Visibility.Collapsed;
                    DownloadButton.Visibility = Visibility.Collapsed;
                    UnFavorButton.Visibility = Visibility.Collapsed;
                    FavoriteButton.Visibility = Visibility.Collapsed;
                    BottomAppBar.Visibility = Visibility.Visible;
                    BottomAppBar.IsOpen = true;
                    SendMail.Visibility = Visibility.Visible;
                }
                else
                {
                    BottomAppBar.Visibility = Visibility.Collapsed;
                }
            }
            else
            {
                BottomAppBar.Visibility = Visibility.Collapsed;
            }
        }

    }
}
